package com.twu.biblioteca.service;

import com.twu.biblioteca.IBookDao;
import com.twu.biblioteca.modal.Book;

public class BookService {
    private static final String format = "| %-5d | %-28s | %-15s | %-4d |%n";
    private final String separateLine = String.format("+-------+------------------------------+-----------------+------+%n");
    private IBookDao bookDao;

    public void setBookDao(IBookDao bookDao) {
        this.bookDao = bookDao;
    }

    public String listBooks() {
        StringBuilder stringBuilder = new StringBuilder();

        stringBuilder.append(separateLine).append(String.format("|Book ID|            Book Name         |       Author    | Year |%n")).append(separateLine);

        for (Book book : bookDao.getBooks()) {
            if (book.getAvailable()) {
                stringBuilder.append(String.format(format, book.getBookID(), book.getName(), book.getAuthor(), book.getPublishYear()));
            }
        }

        stringBuilder.append(separateLine);
        return stringBuilder.substring(0, stringBuilder.length() - 1);
    }

    public Boolean checkout(int bookID) {
        Boolean flagValue = false;
        for (Book book : bookDao.getBooks()) {
            if (book.getBookID() == bookID && book.getAvailable()) {
                book.changeAvailableStatus();
                flagValue = true;
                break;
            }
        }
        return flagValue;
    }

    public Boolean returnBook(int bookID) {
        Boolean flagValue = false;
        for (Book book : bookDao.getBooks()) {
            if (book.getBookID() == bookID && !book.getAvailable()) {
                book.changeAvailableStatus();
                flagValue = true;
                break;
            }
        }
        return flagValue;
    }
}
